<template>
	<view style="padding: 15px;">

		<u-form labelPosition='top' labelWidth='700rpx' :model="formState" name="basic" layout="horizontal"
			:labelCol="{span:7}" :wrapperCol="{span: 13, offset: 0}" :rules="rules" ref="uForm">
			<u-collapse :value="['1','2','3']" ref='coll'>
				<!-- <u-collapse-item name="1" title="点位信息" icon="https://project.gxrunxiang.com/cdn/cell.png"> -->
				<u-form-item label="设施名称" name="Name" prop="Name"  :required="true" >
					<u--input v-model="formState.Name" />
				</u-form-item>
				<u-form-item label="市" name="City">
					<u--input v-model="formState.City" :disabled="true"/>
				</u-form-item>
				<u-form-item label="区/县" name="District">
					<u--input v-model="formState.District" :disabled="true"/>
				</u-form-item>
				<u-form-item label="地址" name="Addr">
					<u--input v-model="formState.Addr" />
				</u-form-item>
				<u-form-item label="类型" @click="showpicker=true" :required="true" name="Type"  prop="Type">
					<u--input v-model="formState.Type" disabledColor="#ffffff" disabled />
				</u-form-item>
				<u-form-item label="机房等级" @click="showlevel=true" v-if="formState.Type == '机房'">
					<u--input v-model="formState.MachineRoomType" disabledColor="#ffffff" disabled />
				</u-form-item>
				<u-form-item label="备注" name="Remark">
					<u--input allow-half v-model="formState.Remark" />
				</u-form-item>
				<u-form-item label="纬度" name="Lat" >
					<u--input allow-half v-model="formState.Lat" :min="0" />
				</u-form-item>
				<u-form-item label="经度" name="Lng" >
					<u--input allow-half v-model="formState.Lng" :min="0" />
				</u-form-item>
				<u-action-sheet :show="showpicker" :actions="columns" title="请选择类型" @close="showpicker = false"
					@select="typeSelect">
				</u-action-sheet>
				<u-action-sheet :show="showlevel" :actions="levelColumns" title="请选择机房等级" @close="showlevel = false"
					@select="levelSelect">
				</u-action-sheet>
				</u-collapse-item>

				<u-collapse-item name="3" title="室内照片" icon="https://project.gxrunxiang.com/cdn/image.png">
					<u-upload :sizeType="['compressed']" :fileList="fileList1" @afterRead="afterRead"
						@delete="deletePic" name="1" multiple :maxCount="1000" itype='室内照片'></u-upload>
					<u-album :urls="imagesurls1"></u-album>
				</u-collapse-item>
				<u-collapse-item name="3" title="室外照片" icon="https://project.gxrunxiang.com/cdn/image.png">
					<u-upload :sizeType="['compressed']" :fileList="fileList2" @afterRead="afterRead"
						@delete="deletePic" name="2" multiple :maxCount="1000" itype='室外照片'></u-upload>
					<u-album :urls="imagesurls2"></u-album>
				</u-collapse-item>
				<u-collapse-item name="3" title="设备照片" icon="https://project.gxrunxiang.com/cdn/image.png">
					<u-upload :sizeType="['compressed']" :fileList="fileList3" @afterRead="afterRead"
						@delete="deletePic" name="3" multiple :maxCount="1000" itype='设备照片'></u-upload>
					<u-album :urls="imagesurls3"></u-album>
				</u-collapse-item>
				<u-collapse-item name="3" title="图纸" icon="https://project.gxrunxiang.com/cdn/image.png">
					<u-upload :sizeType="['compressed']" :fileList="fileList4" @afterRead="afterRead"
						@delete="deletePic" name="4" multiple :maxCount="1000" itype='图纸'></u-upload>
					<u-album :urls="imagesurls4"></u-album>
				</u-collapse-item>
				<u-collapse-item name="3" title="其它材料" icon="https://project.gxrunxiang.com/cdn/image.png">
					<u-upload :sizeType="['compressed']" :fileList="fileList5" @afterRead="afterRead"
						@delete="deletePic" name="5" multiple :maxCount="1000" itype='其它材料'></u-upload>
					<u-album :urls="imagesurls5"></u-album>
				</u-collapse-item>
				<u-collapse-item name="3" title="节点视频(视频时间请勿超过2分钟或大小超过30M)" icon="https://project.gxrunxiang.com/cdn/image.png">
					<u-upload :sizeType="['compressed']" :fileList="fileList6" @afterRead="afterRead"
						@delete="deletePic" name="6" multiple :maxCount="1000" itype='节点视频' accept="video"></u-upload>
				</u-collapse-item>
			</u-collapse>
			<br>
			<p>
				<u-button type="primary" text="保存" @click="save"></u-button>
			</p>
		</u-form>
		<u-notify ref="uNotify"></u-notify>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/common/config.js'
	import {
		mapGetters
	} from 'vuex'
	import coordtransform from 'coordtransform'
	import {
		addLinePathNode,
		GetListByParent,
		guid,
		getLinePathNodelist,
		LinePathNodeUpdate,
		getfilebyoutid,
		GetAddrByLatlng
	} from '@/common/api.js'
	export default {
		data() {
			return {
				userinfo: {},
				formState: {
					Addr: "",
					City: "",
					District: ""
				},
				fileList1: [],
				fileList2: [],
				fileList3: [],
				fileList4: [],
				fileList5: [],
				fileList6: [],
				imagesurls1: [],
				imagesurls2: [],
				imagesurls3: [],
				imagesurls4: [],
				imagesurls5: [],
				buildid: null,
				id: null,
				notifyData: {
					message: '保存成功',
					type: 'success',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 3000,
					safeAreaInsetTop: false
				},
				columns: [],
				levelColumns: [],
				showpicker: false,
				showlevel: false,
				ischange: false,
				NodeId: "",
				Addr: "",
				rules: {
					'Name': {
						type: 'string',
						required: true,
						message: '请填写名称',
						trigger: ['blur', 'change']
					},
					'Type': {
						required: true,
						message: '请填写类型',
						trigger: ['blur', 'change']
					},
				},
				itypelist: {
					"1": "室内照片",
					"2": "室外照片",
					"3": "设备照片",
					"4": "图纸",
					"5": "其它材料",
					"6": "节点视频"
				},
			}
		},
		onLoad(option) {
			this.userinfo = JSON.parse(uni.getStorageSync("$userinfo"))
			GetListByParent("线路节点类型", this.columns)
			GetListByParent("机房等级",this.levelColumns)
			if (option.Id) {
				this.ischange = true
				this.NodeId = option.Id
				this.getchangelist();
				this.imagesurls1 = []
				this.imagesurls2 = []
				this.imagesurls3 = []
				getfilebyoutid(option.Id).then(res => {
					for (var i = 0; i < res.length; i++) {
						if (res[i].MyType == '室内照片') {
							this.imagesurls1.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
						if (res[i].MyType == '室外照片') {
							this.imagesurls2.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
						if (res[i].MyType == '设备照片') {
							this.imagesurls3.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
						if (res[i].MyType == '图纸') {
							this.imagesurls4.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
						if (res[i].MyType == '其它材料') {
							this.imagesurls5.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
					}
					setTimeout(() => {
							// console.log(this.$refs.coll)
							this.$refs.coll.init()
						},
						1000)
				})
			} else {
				this.formState.Id = guid() //option.id
			}
			if (option.lat && option.lng) {
				this.formState.Lat = option.lat
				this.formState.Lng = option.lng
				// var gcj01 = coordtransform.wgs84togcj02(option.lng, option.lat)
				GetAddrByLatlng(option.lat + "," + option.lng).then(res => {
					var arr = res.split(",")
					this.formState.City = arr[0];
					this.formState.District = arr[1];
					this.formState.Addr = arr[2];
				})
			}
			// if (option.id)
			// 	this.getdate(option.id)
			// try {
			// 	let temppoint = JSON.parse(uni.getStorageSync("temppoint"))
			// 	this.formState.Name = temppoint.Name
			// 	this.formState.BuildType = temppoint.BuildType
			// 	this.formState.Idx = parseFloat(temppoint.Idx) + 0.01
			// } catch (e) {}
		},
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			this.$refs.uForm.setRules(this.rules)
		},
		computed: {
			...mapGetters(['user']),
		},
		methods: {
			save() {
				this.$refs.uForm.validate().then(res => {
					if (this.ischange) {
						LinePathNodeUpdate(this.formState).then(res => {
							this.$refs.uNotify.show(this.notifyData)
							setTimeout(() => {
								// uni.reLaunch({
								// 	url: `linepathnode`
								// })
								uni.navigateBack({
										delta:1,
								})
							}, 1000)
						})
					} else {
						addLinePathNode(this.formState).then(res => {
							this.$refs.uNotify.show(this.notifyData)
							setTimeout(() => {
								// uni.reLaunch({
								// 	url: `linepathnode`
								// })
								uni.navigateBack({
										delta:1,
								})
							}, 1000)
						})
					}
				}).catch(errors => {
					uni.$u.toast('请填写必填参数！')
				})
				// this.formState.Buildid=this.buildid
				// uni.setStorageSync("temppoint", JSON.stringify(this.formState))
			},
			goBack() {
				let pages = getCurrentPages(); // 当前页面　　
				// console.log("pages" + pages)
				let beforePage = pages[pages.length - 2]; // 上一页
				uni.navigateBack({
					delta: 1,
					// success: function() {
					// 	// beforePage.myMapView.mounted();
					// 	console.log(beforePage.route)
					// 	console.log(beforePage.getdata)
					// 	// beforePage.getdata(); // 执行上一页的onLoad方法
					// }
				});
			},
			typeSelect(e) {
				this.formState.Type = e.name
			},
			levelSelect(e){
				this.formState.MachineRoomType = e.name
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url,this.itypelist[event.name])
					let item = this[`fileList${event.name}`][fileListLen]
					if(this.itypelist[event.name] == '节点视频'){
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: 'https://project.gxrunxiang.com/cdn/success.png'
						}))
						fileListLen++
					}else{
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
					}				
				}
			},
			uploadFilePromise(url,itype) {
				// console.log(this.user.Id)
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.formState.Id||this.userinfo.Id}&type=${itype}`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.$store.getters.$token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			async getchangelist() {
				let para = {
					Parameters: [{
						FieldName: "Id",
						ConditionalType: "Equal",
						FieldValue: this.NodeId
					}],
					orderBys: ["Id"],
				}
				await getLinePathNodelist("", para).then(res => {
					this.formState = res.data[0]
				})
			}
		}
	}
</script>

<style>

</style>